<template>
  <div class="table">

    <div class="container">
      <div class="handle-box">
        <el-button type="primary" size="mini" @click="delAll">批量删除</el-button>
        <el-button type="primary" size="mini" @click="centerDialogVisible = true">添加用户</el-button>
        <el-input v-model="select_word" size="mini" placeholder="请输入用户名" class="handle-input"></el-input>
      </div>
    </div>

    <!-- 主界面 -->
    <el-table size="mini" ref="multipleTable" border style="width:100%" :data="data" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="用户图片" width="200" align="center">
        <template slot-scope="scope">
          <div class="consumer-img">
            <img :src="getUrl(scope.row.avator)" height=200px>
          </div>
          <el-upload :action="updateUrl(scope.row.id)" :before-upload="beforeAvatorUpload"
            :on-success="handleAvatorSuccess">
            <el-button size="mini">更新图片</el-button>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120" align="center"></el-table-column>
      <el-table-column label="性别" width="50" align="center">
          <template slot-scope="scope">
              {{changeSex(scope.row.sex)}}
          </template>
      </el-table-column>
      <el-table-column prop="phoneNum" label="手机号" width="120" align="center"></el-table-column>
      <el-table-column prop="email" label="电子邮箱" width="120" align="center"></el-table-column>
      <el-table-column label="生日" width="150" align="center">
          <template slot-scope="scope">
              {{attachBirth(scope.row.birth)}}
          </template>
      </el-table-column>
      <el-table-column prop="introduction" label="签名" width="120" align="center"></el-table-column>
      <el-table-column prop="location" label="地区" width="120" align="center"></el-table-column>
      <el-table-column label="收藏" width="80" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="getCollect(data[scope.$index].id)">收藏</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          background
          layout = "total,prev,pager,next"
          :page-size="pageSize"
          :total="tableData.length"
          @current-change="handleCurrentChange"
          >
      </el-pagination>
    </div>

    <!-- 添加用户界面 -->
    <el-dialog title="添加用户" :visible.sync="centerDialogVisible" width="400px" center>
      <el-form :model="registerForm" ref="registerForm" label-width="80px" :rules="rules">
        <el-form-item prop="username" label="用户名" size="mini">
          <el-input v-model="registerForm.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="mini">
          <el-input v-model="registerForm.password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="性别" size="mini">
          <input type="radio" name="sex" value="0" v-model="form.sex">&nbsp;女&nbsp;&nbsp;
          <input type="radio" name="sex" value="1" v-model="form.sex">&nbsp;男
        </el-form-item>
        <el-form-item prop="phoneNum" label="手机号" size="mini">
          <el-input v-model="registerForm.phoneNum" placeholder="手机号" style="width:100%"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱" size="mini">
          <el-input v-model="registerForm.email" placeholder="电子邮箱" style="width:100%"></el-input>
        </el-form-item>
        <el-form-item prop="birth" label="生日" size="mini">
          <el-date-picker type="date" v-model="registerForm.birth" placeholder="选择日期" style="width:100%"></el-date-picker>
        </el-form-item>
        <el-form-item prop="introduction" label="签名" size="mini">
          <el-input v-model="registerForm.introduction" placeholder="签名"></el-input>
        </el-form-item>      
        <el-form-item prop="location" label="地区" size="mini">
          <el-input v-model="registerForm.location" placeholder="地区"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" size="mini" @click="addConsumer">确认</el-button>
        <el-button size="mini" @click="centerDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户界面 -->
    <el-dialog title="修改用户" :visible.sync="editVisible" width="400px" center>
      <el-form :model="form" ref="form" label-width="80px" :rules="rules">
        <el-form-item prop="username" label="用户名" size="mini">
          <el-input v-model="form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" size="mini">
          <el-input v-model="form.password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="性别" size="mini">
          <input type="radio" name="sex" value="0" v-model="form.sex">&nbsp;女&nbsp;&nbsp;
          <input type="radio" name="sex" value="1" v-model="form.sex">&nbsp;男
        </el-form-item>
        <el-form-item prop="phoneNum" label="手机号" size="mini">
          <el-input v-model="form.phoneNum" placeholder="手机号" style="width:100%"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱" size="mini">
          <el-input v-model="form.email" placeholder="电子邮箱" style="width:100%"></el-input>
        </el-form-item>
        <el-form-item prop="birth" label="生日" size="mini">
          <el-date-picker type="date" v-model="form.birth" placeholder="选择日期" style="width:100%"></el-date-picker>
        </el-form-item>
        <el-form-item prop="introduction" label="签名" size="mini">
          <el-input v-model="form.introduction" placeholder="签名"></el-input>
        </el-form-item>      
        <el-form-item prop="location" label="地区" size="mini">
          <el-input v-model="form.location" placeholder="地区"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" size="mini" @click="editSave">确认</el-button>
        <el-button size="mini" @click="editVisible = false">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="删除用户" :visible.sync="delVisible" width="300px" center>
      <div align="center">删除不可恢复，是否确认删除</div>
      <span slot="footer">
        <el-button type="primary" size="mini" @click="deleteRow">确认</el-button>
        <el-button size="mini" @click="delVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mixin } from '../mixins/index';
import { getAllConsumer,setConsumer,updateConsumer,delConsumer,getUserOfId } from "@/api/index"
export default {
  mixins: [mixin],
  name: '',
  components: {},
  props: {},
  data () {
    return {
      centerDialogVisible: false, //添加弹窗是否显示
      editVisible: false,         //编辑弹窗是否显示
      delVisible: false,          //删除弹窗是否显示
      registerForm: {             //添加框
        username: '',
        password: '',
        sex: '1',
        phoneNum: '',
        email: '',
        birth: '',
        introduction: '',
        location: ''
      },
      form: {        //编辑框
        id: '',
        username: '',
        password: '',
        sex: '',
        phoneNum: '',
        email: '',
        birth: '',
        introduction: '',
        location: ''
      },
      tableData: [], // 用户数据表
      tempData: [], // 根据用户名搜索时用的用户数据表
      select_word: '', // 搜索的用户名
      pageSize: 10, // 分页每页大小
      currentPage: 1, // 当前页
      idx: -1, // 当前选择的用户
      multipleSelection: [],   //哪些项已经打勾
      // 输入框规则
      rules: {
        username: [
          {required: true,message: '请输入用户名',trigger: 'blur'}
        ],
        password: [
          {required: true,message: '请输入密码',trigger: 'blur'}
        ],
        phoneNum: [
          {required: true,message: '请输入手机号',trigger: 'blur'}
        ],
        email: [
          {required: true,message: '请输入电子邮箱',trigger: 'blur'},
          {type: 'email',message:'请输入正确的电子邮箱地址',trigger:['blur','change']}
        ],
        introduction: [
          {required: true,message: '请输入签名',trigger: 'blur'}
        ],
        location: [
          {required: true,message: '请输入地区',trigger: 'blur'}
        ]                
      }
    }
  },
  computed: {
    //计算当前搜索结果表里的数据
    data(){
        return this.tableData.slice((this.currentPage - 1) * this.pageSize,this.currentPage * this.pageSize)
    }
  },
  watch: {
    //搜索框里面的内容发生变化的时候，搜索结果table列表的内容跟着它的内容发生变化
    select_word: function() {
      if(this.select_word == ''){
        this.tableData = this.tempData;
      } else {
        this.tableData = [];
        for(let item of this.tempData) {
          if(item.name.includes(this.select_word)){
            this.tableData.push(item);
          }
        }
      }
    }
  },
  created () {
    this.getData();
  },
  methods: { 
    // 获取全部用户
    getData() {
      this.tableData = [];
      this.tempData = [];
      getAllConsumer().then(res =>{
        this.tableData = res;
        this.tempData = res;
        this.currentPage = 1;
      })
    },
    // 添加用户
    addConsumer() {
      this.$refs['registerForm'].validate(valid => {
        if(valid){
          let d = this.registerForm.birth;
          let datatime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
          let params = new URLSearchParams();
          params.append('username',this.registerForm.username);
          params.append('password',this.registerForm.password);
          params.append('sex',this.registerForm.sex);
          params.append('phoneNum',this.registerForm.phoneNum)
          params.append('email',this.registerForm.email);
          params.append('birth',datatime);
          params.append('introduction',this.registerForm.introduction);
          params.append('location',this.registerForm.location);
          params.append('avator',`/img/user.png`);
          setConsumer(params)
          .then(res => {
            if(res.code == 1){
              this.getData();
              this.notify("添加成功","success");
            } else {
              his.notify("添加失败","error");
            }
          })
          .catch(err => {
            console.log(err)
          });
          this.centerDialogVisible = false;
        }
      })
    },
    //获取当前页
    handleCurrentChange(val){
        this.currentPage = val;
    },
    //弹出编辑页面
    handleEdit(row) {
      this.editVisible = true;
      this.form = {
        id: row.id,
        username: row.username,
        password: row.password,
        sex: row.sex,
        phoneNum: row.phoneNum,
        email: row.email,
        birth: row.birth,
        introduction: row.introduction,
        location: row.location
      }
    },
    // 保存编辑
    editSave() {
      this.$refs['form'].validate(valid =>{
        if(valid){
          let d = new Date(this.form.birth);
          let datetime = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
          let params = new URLSearchParams();
          params.append('id',this.form.id);
          params.append('username',this.form.username);
          params.append('password',this.form.password);
          params.append('sex',this.form.sex);
          params.append('phoneNum',this.form.phoneNum);
          params.append('email',this.form.email);
          params.append('birth',datetime);
          params.append('introduction',this.form.introduction);
          params.append('location',this.form.location);
          updateConsumer(params)
          .then(res => {
            if(res.code == 1){
              this.getData();
              this.notify("修改成功","success");
            }else{
              this.notify("修改失败","error");
            }
          })
          .catch(err => {
            console.log(err)
          })
          this.editVisible = false;
          } 
        })
    },
    // 更新图片路径
    updateUrl(id){
      return `${this.$store.state.HOST}/consumer/updateConsumerPic?id=${id}`;
    },
    // 删除一个用户
    deleteRow() {
      delSinger(this.idx)
      .then(res => {
        if(res) {
          this.getData();
          this.notify("删除成功","success");
        } else {
          this.notify("删除失败","error");
        }
      })
      .catch(err => {
        console.log(err);
      }) 
      this.delVisible = false;
    },
      //转向该用户的收藏列表
      getCollect(id){
        this.$router.push({path: '/collect',query:{id}})
      }
  }
}
</script>
<style>
.handle-box {
  margin-bottom: 10px;
}
.handle-input{
    width: 300px;
    display: inline-block;
}
</style>